package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.exception.TBKException;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static cn.taobaoke.restful.util.Constants.IMAGE_ROOT;

/**
 * @author yangzuo
 * @since 2017-05-06 13:59
 */
@RestController
@RequestMapping("/api/files")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ImageUploadController extends BaseController {

    @PostMapping("/images")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        logger.info("上传图片文件操作: /api/files/image");
        if (!file.isEmpty()) {
            try {
                String filename = changeFileName(file.getOriginalFilename());
                Files.copy(file.getInputStream(), Paths.get(IMAGE_ROOT, filename));
                return wrapObj(filename);
            } catch (IOException e) {
                throw new TBKException("上传图片失败", e);
            }
        }
        return wrapVoid();
    }

    @PostMapping("/images/multiple")
    public Result uploadMultipleFiles(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        List<String> results = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                String filename = changeFileName(file.getOriginalFilename());
                Files.copy(file.getInputStream(), Paths.get(IMAGE_ROOT, filename));
                results.add(filename);
            }
            return wrapObj(results);
        } catch (IOException e) {
            throw new TBKException("上传图片失败", e);
        }
    }

    @GetMapping("/images/{filename:.+}")
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            ResponseEntity entity = ResponseEntity.ok(
                    resourceLoader.getResource("file:" + Paths.get(IMAGE_ROOT, filename).toString()));
            return entity;
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    private String changeFileName(final String filename) {
        int index = filename.lastIndexOf(".");
        String suffix = "";
        if (index != -1) {
            suffix = filename.substring(index);
        }
        UUID uuid = UUID.randomUUID();
        return uuid.toString() + suffix;
    }

    private final @NonNull
    ResourceLoader resourceLoader;

    private static Logger logger = LogManager.getLogger(ExcelFileUploadController.class);
}
